package cn.org.donald.framework.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author : Donald
 * @since : 2021/1/20 14:20
 */
public class CommandUtil {


    /**
     * @param localPath   本地路径
     * @param cloneUrl    git 地址
     * @param projectName 项目名称
     * @return
     */
    public static String getGitDefaultCommand(String localPath, String cloneUrl, String projectName) {
        // cd 到指定路径
        String command0 = "cd " + localPath;
        // rm -rf projectName
        String command1 = "rm -rf " + projectName;
        // git clone
        String command2 = "git clone " + cloneUrl;
        // cd 到project root
        String command3 = "cd " + projectName;
        // mvn install
        String command4 = "mvn install";

        return command0 + "\n" +
                command1 + "\n" +
                command2 + "\n" +
                command3 + "\n" +
                command4 + "\n";
    }

    public static String getDefaultMavenCommand(){
        return "mvn clean\nmvn install\n";
    }

    /**
     * execute linux's command
     *
     * @param command command line
     * @return
     */
    public static String executeLinuxCommand(String command) throws IOException {
        String[] shell = new String[]{"/bin/sh", "-c", command};
        return executeCommand(shell);
    }

    public static String executeWindowsCommand(String command) throws IOException {
        String[] shell = new String[]{"cmd.exe", "/c", command};
        return executeCommand(shell);
    }

    private static String executeCommand(String ... command) throws IOException {
        StringBuilder sb = new StringBuilder();
        Process exec = Runtime.getRuntime().exec(command);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line).append("\n");
        }
        return sb.toString();
    }
}
